import { useEffect, useState } from 'react';
import { Form, Space, Col, Table, Input, Button, Tag, Popconfirm, Row, Select, Divider } from 'antd';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import type { PopconfirmProps } from 'antd';
import { messageApi } from '../../utils/message';
import { formatSchoolsType, } from '../../utils/format';
import type { SchoolItem } from '../../types/school';
import { useAuthStore } from '../../store/authStore';
import { getManufacturerList } from '../../api/manufacturer';
import SchoolsModal from './modal/schoolsModal';
import { searchSchoolsList, updateSchool } from '../../api/school';
import { useNavigate } from 'react-router-dom';

const School = () => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false)
    const [modelVisible, setModelVisible] = useState(false)
    const [temRecord, setTemRecord] = useState<SchoolItem>()
    const { userInfo } = useAuthStore();
    const [manufacturerList, setManufacturerList] = useState<{ value: number, label: string }[]>([])
    const navigate = useNavigate();
    const [dataSource, setDataSource] = useState<SchoolItem[]>([])


    const confirmPopconfirm: PopconfirmProps['onConfirm'] = (): void => {
        if (!temRecord) return
        const next = { ...temRecord, status: temRecord.status === 0 ? 1 : 0 }
        updateSchool(next).then(res => {
            messageApi.success('操作成功！')
            if (userInfo?.role === 'super_admin') {
                handleSearch()
                return
            }
            fetchData()
        })

    }

    const columns = [
        {
            title: '学校名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '类型',
            dataIndex: 'type',
            render: (value: SchoolItem['type']) => {
                if (value === undefined || value === null) return '---';
                return formatSchoolsType(value)
            }

        },
        {
            title: '学年制',
            dataIndex: 'education_years',
            key: 'education_years',

        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 120,
            render: (value: SchoolItem['status']) => {
                return value === 0 ? <Tag color="red">禁用</Tag> : <Tag color="green">启用</Tag>
            }
        },
        {
            title: '操作',
            dataIndex: 'options',
            width: 120,
            render: (value: SchoolItem['status'], record: SchoolItem) => {
                let color: "green" | "danger" = 'green';
                let text = '启用';
                if (record.status === 1) {
                    color = 'danger';
                    text = '禁用'
                }
                return <Space size={'small'}>
                    <Popconfirm
                        key={record.id}
                        title={`要${text}学校？`}
                        onConfirm={confirmPopconfirm}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button color={color} variant="text" onClick={() => setTemRecord(record)}>
                            {text}
                        </Button>
                    </Popconfirm>
                    <Divider type="vertical" />
                    <Button color={'primary'} variant="text" onClick={() => navigate(`/school/detail?id=${record.id}`)}>
                        详情
                    </Button>
                </Space>

            }
        }
    ];

    const fetchData = async () => {
        try {
            setLoading(true);
            // 并行请求数据
            // const res = await getManufacturerWithSchools();
            // setDataSource(res.manufacturers);
        } catch (error) {
            console.error('获取首页数据失败', error);
        } finally {
            setLoading(false);
        }
    };
    const handleReset = () => {
        form.resetFields(['name', 'status'])
        handleSearch()
    }
    const renderForm = () => {
        return <Form
            form={form}
            initialValues={{}}
        >
            <Row>
                {userInfo?.role === 'super_admin' && <Col span={6} >
                    <Form.Item label="所属厂商" name="manufacturer_id">
                        <Select
                            options={manufacturerList}
                        />
                    </Form.Item>
                </Col>}
                <Col span={6} offset={1}>
                    <Form.Item label="学校名称" name="name">
                        <Input placeholder="学校名称" />
                    </Form.Item>
                </Col>
                <Col span={3} offset={1}>
                    <Form.Item label="状态" name='status'>
                        <Select
                            allowClear
                            options={[
                                { value: 0, label: '禁用' },
                                { value: 1, label: '启用' },
                            ]}
                        />
                    </Form.Item>
                </Col>
                <Col span={6} offset={1}>
                    <Space>
                        <Button icon={<SearchOutlined />} type="primary" onClick={handleSearch}>查询</Button>
                        <Button type="primary" onClick={handleReset}>重置</Button>
                    </Space>
                </Col>
            </Row>
            <Row>
                <Col span={24}>
                    <Form.Item>
                        <Button icon={<PlusOutlined />} type="primary" onClick={() => setModelVisible(true)}>新增</Button>
                    </Form.Item>
                </Col>
            </Row>

        </Form>
    }

    // 获取统计数据
    useEffect(() => {

        fetchManufacturerlist();
    }, []);

    const fetchManufacturerlist = () => {
        if (!userInfo) {

            return
        }
        if (userInfo.role !== 'super_admin') {
            fetchData();
            return
        }

        getManufacturerList().then(res => {
            const next = res.manufacturers.map(t => ({ value: t.id, label: t.name }))
            setManufacturerList(next)
            form.setFieldValue('manufacturer_id', next[0].value)
            handleSearch();
        })
    }


    const modalCallback = () => {
        fetchData();
        setModelVisible(false)

    }

    const handleSearch = async () => {
        const next = form.getFieldsValue(['manufacturer_id', 'name', 'status'])
        try {
            setLoading(true);
            const res = await searchSchoolsList(next);
            setDataSource(res.schools);
        } catch (error) {
            console.error('获取数据失败', error);
        } finally {
            setLoading(false);
        }
    }



    return (
        <div>
            <div>
                {renderForm()}
            </div>
            <div >
                <Table loading={loading} dataSource={dataSource} columns={columns} />
            </div>
            <SchoolsModal manufacturerList={manufacturerList} callback={modalCallback} visible={modelVisible} handleCancel={() => setModelVisible(false)}></SchoolsModal>
        </div>
    );
};

export default School;
